package com.cordershy.service;

import com.cordershy.mapper.incomeMapper;
import com.cordershy.pojo.income;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class incomeService {
    @Autowired
    incomeMapper incomeMapper;
    @Transactional(propagation = Propagation.REQUIRED)
    public List<income> selectAll(){
        return incomeMapper.selectAll();
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @Cacheable(value = "accountCache",key = "'income'+#incomeyear+#incomemonth")
    public List<income> selectByDate(String incomeyear,String incomemonth,String username){
        List<income> incomes = incomeMapper.selectByDate(incomeyear,incomemonth,username);
        Collections.reverse(incomes);
        Collections.sort(incomes);
        return incomes;
    }
    @Transactional
    @Cacheable(value = "accountCache",key = "'incomeid'+#incomeid")
    public income selectById(int incomeid){
        return incomeMapper.selectById(incomeid);
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @CachePut(value = "accountCache",key = "'incomeid'+#income.incomeid")
    public income addIncome(income income){
        incomeMapper.insert(income);
        return income;
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @CachePut(value = "accountCache",key = "'incomeid'+#income.incomeid")
    public income updateIncome(income income){
        income temp = selectById(income.getIncomeid());
        if (temp!=null){
            incomeMapper.update(income);
        }else{
            return null;
        }
        return income;
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @CacheEvict(value = "accountCache",key = "'incomeid'+#incomeid")
    public int deleteIncome(int incomeid){
        return incomeMapper.delete(incomeid);
    }
}
